<template>
  <el-dialog title="分配数据权限" :close-on-click-modal="false" :visible.sync="visible">
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="角色名称" prop="userName">
        <el-input :disabled="true" v-model="dataForm.roleName"></el-input>
      </el-form-item>

      <el-form-item label="角色编码" prop="roleIdList">
        <el-input :disabled="true" v-model="dataForm.alias"></el-input>
      </el-form-item>

      <el-form-item label="权限范围">
        <el-select v-model="dataForm.qxValue" placeholder="请选择" @change="initData(dataForm.qxValue)">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item size="mini" label="数据权限" v-show="dataForm.qxValue==2">
        <el-tree
          :data="deptList"
          :props="deptListTreeProps"
          node-key="deptId"
          ref="deptListTree"
          :default-expand-all="true"
          show-checkbox
        ></el-tree>
      </el-form-item>
    </el-form>

    <div></div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
import { treeDataTranslate } from "@/utils";
export default {
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    };
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("确认密码不能为空"));
      } else if (this.dataForm.password !== value) {
        callback(new Error("确认密码与密码输入不一致"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      dataForm: {
        id: 0,
        roleName: "",
        alias: "",
        remark: "",
        qxValue: ""
      },
      dataRule: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        alias: [
          { required: true, message: "角色编码不能为空", trigger: "blur" }
        ]
      },

      menuList: [],
      deptList: [],
      daptListOld:[],
      deptListTreeProps: {
        label: "deptName",
        children: "children"
      },

      options: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },

        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      deptIds: "",
      tempKey: -666666
    };
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      if (this.dataForm.id) {
        this.$http({
          url: this.$http.adornUrl("/sys/dept/select"),
          method: "get",
          params: this.$http.adornParams()
        }).then(({ data }) => {
          //初始化装载数据
          this.deptList = treeDataTranslate(data.deptList, "deptId");
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
            this.$refs.deptListTree.setCheckedKeys([]);
          });
        }).then(() => {
            this.$http({
              url: this.$http.adornUrl(`/sys/role/info/${this.dataForm.id}`),
              method: "get",
              params: this.$http.adornParams()
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.menuList=data.role.menuIdList;
                this.dataForm.roleName = data.role.roleName;
                this.dataForm.alias = data.role.alias;
                this.dataForm.remark = data.role.remark;
                this.daptListOld=data.role.deptIdList;
                this.dataForm.qxValue=data.role.dataScope==null?"5":data.role.dataScope;
                var idx = data.role.deptIdList.indexOf(this.tempKey);
                if(data.role.dataScope==2) {
                  this.$refs.deptListTree.setCheckedKeys(data.role.deptIdList);
                }
                if (idx !== -1) {
                  data.role.deptIdList.splice(
                    idx,
                    data.role.deptIdList.length - idx
                  );
                }
              }
            })
          })
      }
    },
    initData(value){
      if(value==2){
        this.$refs.deptListTree.setCheckedKeys(this.daptListOld);
      }
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/role/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              roleId: this.dataForm.id || undefined,
              roleName: this.dataForm.roleName,
              alias: this.dataForm.alias,
              remark: this.dataForm.remark,
              dataScope: this.dataForm.qxValue,
              deptIdList:this.dataForm.qxValue==2? [].concat(
                this.$refs.deptListTree.getCheckedKeys(),
                [this.tempKey]
              ):[],
              menuIdList:this.menuList
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
